<template>
    <div>
      <!-- 搜索结果页-头部导航 -->
      <div class="search-result-container">
        <!-- 点击实现后退效果 -->
        <van-nav-bar
          title="搜索结果"
          left-arrow
          @click-left="$router.go(-1)"
          fixed
        />
      </div>
      <van-list
      v-model="loading"
      :finished="finished"
      :immediate-check="false"
      finished-text="没有更多了"
      offset="50"
      @load="onLoad"
    >
      <!-- 文章列表 -->
      <article-item
        v-for="item in articlesList"
        :key="item.art_id"
        :obj="item"
         @click.native="$router.push(`/article_detail?aid=${item.art_id}`)"
      ></article-item>
    </van-list>
    </div>
</template>

<script>
import { searchAPI } from '@/api'
import ArticleItem from '../Home/components/ArticleItem.vue'
import { timeAgo } from '@/utils/date.js'
export default {
  components: { ArticleItem },
  name: 'SearchResult',
  data () {
    return {
      articlesList: [],
      timeAgo,
      loading: false,
      finished: false,
      page: 1 // 页码
    }
  },
  methods: {
    onLoad () {
      // 触发onLoad时调用数据请求方法
      if (this.articlesList.length > 0) {
        this.page++
        this.getArticleList()
      }
    },
    // 封装请求接口
    async getArticleList () {
      const res = await searchAPI({
      // keywords来源于router/index.js你定义的动态路由参数名
        q: this.$route.params.keywords,
        page: this.page
      })
      console.log(res)
      // 将数据进行处理，把时间转成多久多久之前
      res.data.data.results.forEach((item) => {
        item.pubdate = this.timeAgo(item.pubdate)
      })
      // 如果无数据
      if (res.data.data.results.length === 0) {
        // 告诉list组件直接底部显示没有更多数据
        this.finished = true
      } else {
        this.articlesList = [...this.articlesList, ...res.data.data.results]
        // 等待数据加载完毕后
        this.loading = false
      }
    }
  },
  // 调用获取搜索结果接口
  async created () {
    this.getArticleList()
  }
}
</script>

<style lang="less" scoped>
.search-result-container {
  padding-top: 46px;
}
</style>
